package sdk.org.apache.shiro.G1_工具类.C01_创建SecurityManager;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.mgt.ServletContainerSessionManager;

import com.titan.core.utils.debug.Timer;
import com.titan.core.utils.io.ConsoleUtils;

import sdk.org.apache.shiro.utils.ShiroUtils;

public class 使用Java代码实现SecurityManager {
    public static void main(String[] args) {
        Timer timer = Timer.$();
        try {
            run(timer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            timer.print("执行总用时");
            System.exit(0);
        }
    }
    private static void run(Timer timer) throws Exception {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // 设置authenticator，身份认证 / 登录，验证用户是不是拥有相应的身份
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        securityManager.setAuthenticator(authenticator);
        
        // 设置authorizer，授权，即权限验证
        ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer();
        authorizer.setPermissionResolver(new WildcardPermissionResolver());
        securityManager.setAuthorizer(authorizer);

        SimpleAccountRealm realm = new SimpleAccountRealm();
        realm.addAccount("aaa", "111");
        realm.addAccount("bbb", "222");
        securityManager.setRealm(realm);
        
        SecurityUtils.setSecurityManager(securityManager);
        
        // 登录
        ShiroUtils.login("aaa", "111", true);
        
        // 断言用户已经登录
        Subject currentUser = SecurityUtils.getSubject();
        ConsoleUtils.log("用户 ["+currentUser.getPrincipal()+"] 的登录状态："+currentUser.isAuthenticated());
        
        // 用户退出
        ShiroUtils.logout();
    }
}
